package com.shaoyu.oauth2.service.impl;

import cn.hutool.json.JSONUtil;
import com.shaoyu.oauth2.entity.SysUser;
import com.shaoyu.oauth2.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * Description:
 *
 * @author mac
 * @date 2021/2/26 下午4:39
 * @since JDK 1.8
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserService userService;


    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userService.getByUsername(username);
        if (null == sysUser) {
            log.warn("用户{}不存在", username);
            throw new UsernameNotFoundException(username);
        }
        User user = new User(sysUser.getUsername(), passwordEncoder.encode(sysUser.getPassword()), AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));

        log.info("登录成功！用户: {}", JSONUtil.toJsonStr(user));

        return user;
    }
}
